package snippets.cse524.activeDates;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.HashSet;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;

import snippets.utils.Utils;

public class EntitySourceMappingCanonifier {

	/**
	 * @param args
	 * @throws FileNotFoundException
	 */
	public static void main(String[] args) throws FileNotFoundException {
		// TODO Auto-generated method stub
		System.err.println("Reading canonical names ...");
		Map<String, String> canonicalNames = Utils
				.readCanonicalNames(new FileInputStream(new File(args[0])));

		// read all recognized enititie for which we have ranks
		Scanner input;
		Set<String> rankedEntities = new HashSet<String>();

		input = new Scanner(new FileInputStream(new File(args[1])));

		while (input.hasNextLine()) {
			String line = input.nextLine();

			String[] parts = StringUtils.split(line, "\t");

			rankedEntities.add(parts[0].trim());
		}

		input = new Scanner(System.in);

		while (input.hasNextLine()) {
			String line = input.nextLine();

			String[] parts = StringUtils.split(line, ":\t");

			if (parts.length != 4) {
				System.err.println("Invalid entity source mapping line: "
						+ line);
				continue;
			}

			String entityName = parts[2].trim();
			String entityNameUs = StringUtils.replace(entityName, " ", "_");

			if (!rankedEntities.contains(entityNameUs)) {
				if (!canonicalNames.containsKey(entityName.toLowerCase())) {
					System.err.println("Skipping entity : " + entityName);
					continue;
				}

				// we have a canonical form

				if (!rankedEntities.contains(canonicalNames.get(entityName))) {
					System.err.println("Skipping entity : " + entityName);
					continue;
				}

				// the canonical form is ranked
				entityNameUs = canonicalNames.get(entityName);
			}

			System.out.println(StringUtils.join(new String[] {
					parts[0],
					parts[1],
					entityNameUs,
					parts[3]
			}, '\t'));
		}
	}
}
